package cloud.hedou.abp.remote

import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.Response
import retrofit2.Invocation
import retrofit2.http.Url

class DynamicUrlInterceptor(private val hosts: Map<Int, String>) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val invocation = request.tag(Invocation::class.java)
        if (invocation != null) {
            val httpUrl = getNewHttpUrl(invocation, request.url())
            if (httpUrl != null) {
                request = request.newBuilder().url(httpUrl).build()
            }
        }
        return chain.proceed(request)
    }

    private fun getNewHttpUrl(invocation: Invocation, originalHttpUrl: HttpUrl): HttpUrl? {
        val method = invocation.method()
        val annotationList = method.parameterAnnotations.flatten()
        if (annotationList.contains(Url())) {
            return null
        }
        val apiAnnotation = method.getAnnotation(Api::class.java)
            ?: method.declaringClass.getAnnotation(Api::class.java)
        if (apiAnnotation != null) {
            val port = apiAnnotation.port
            val httpUrl = hosts[port]?.let(HttpUrl::get)
            return if (httpUrl != null) {
                // 将访问路径添加到指定的url后面
                val preceding = httpUrl.encodedPath().takeIf { it != "/" } ?: ""
                val encodedPath = originalHttpUrl.encodedPath()
                return originalHttpUrl.newBuilder()
                    .host(httpUrl.host())
                    .port(httpUrl.port())
                    .encodedPath("$preceding$encodedPath")
                    .build()
            } else {
                // 修改访问端口
                originalHttpUrl.newBuilder().port(port).build()
            }
        }
        return null
    }

}